package com.mongo.util;

import com.tanhua.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * 用于mongoDB自动增长序列
 */
@Component
public class MongoIdWorker {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * @param collName 集合名字
     * @return
     */
    public Long getNextId(String collName){
        //1 创建Query对象
        Query query = new Query(Criteria.where("collName").is(collName));
        //2 创建update对象
        Update update = new Update();
        update.inc("seqId",1);//设置seqId每次自增1
        //3 创建FindAndModify对象
        FindAndModifyOptions fmo = new FindAndModifyOptions();
        //4 设置修改属性
        fmo.upsert(true);//true表示：如果找不到对应的记录，就自动插入一条数据
        fmo.returnNew(true);//true表示：返回更新后的数据
        //5 执行查询
        Sequence sequence = mongoTemplate.findAndModify(query, update, fmo, Sequence.class);
        //6 返回id
        return sequence.getSeqId();
    }



}
